package controller

import (
	"gitee.com/xuxusheng/be-order/exception"
	"gitee.com/xuxusheng/be-order/resolver"
	"github.com/gin-gonic/gin"
	"github.com/graphql-go/graphql"
	"github.com/graphql-go/handler"
	"log"
	"net/http"
)

func GraphHandler(c *gin.Context) {

	// 判断中间件中是否抛出了错误
	if len(c.Errors) > 0 {
		return
	}

	// 构造 schema
	schema, err := graphql.NewSchema(resolver.SchemaConfig)
	if err != nil {
		log.Fatalf("构造 graphql schema 失败：%v", err)
	}

	// get query
	opts := handler.NewRequestOptions(c.Request)

	params := graphql.Params{
		Schema:         schema,
		RequestString:  opts.Query,
		VariableValues: opts.Variables,
		OperationName:  opts.OperationName,
		RootObject:     map[string]interface{}{},
		Context:        c,
	}

	// 执行
	r := graphql.Do(params)

	errMeta := exception.ErrMeta{
		ErrCode:    0,
		StatusCode: http.StatusOK,
	}
	if r.HasErrors() {
		// 出错
		err := r.Errors[0]

		// errCode
		if code, ok := err.Extensions["errCode"].(int); ok {
			errMeta.ErrCode = code
		} else {
			errMeta.ErrCode = exception.ServerErrCode
		}

		// statusCode
		if status, ok := err.Extensions["status"].(int); ok {
			errMeta.StatusCode = status
		} else {
			errMeta.StatusCode = http.StatusInternalServerError
		}
		c.Error(&gin.Error{
			Err:  err,
			Type: gin.ErrorTypePublic,
			Meta: &errMeta,
		})
	}
	c.Set("data", r.Data)

}
